package cn.com.liu.disruptor;

import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

public class LongEventMain {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		//创建工厂
		EventFactory<LongEvent> eventFactory = new LongEventFactory();
		//创建ringBufferSize，也就是RingBuffer的大小，必须是2的N次方
		int ringBufferSize = 1024*1024;
		//创建缓冲池
		ExecutorService threadFactory = Executors.newCachedThreadPool();
		//
		ProducerType producerType = ProducerType.SINGLE;
		//
		WaitStrategy waitStrategy = new YieldingWaitStrategy();
		//创建disruptor:
		/*
		 * 1.第一个为工厂类，创建事件类
		 * 2.第二个为缓冲区的大小
		 * 3.第三个为线程池，进行disruptor内部的数据接收处理调度
		 * 4.第四个为：ProducerType.SINGLE（单生产者） ProducerType.MULTI（多生产者）
		 * 5.第五个参数是生产和消费的策略：
		 * BlockingWaitStrategy 是最低效的策略，但其对CPU的消耗最小并且在各种不同部署环境中能提供更加一致的性能表现
		 * SleepingWaitStrategy的性能表现跟BlockingWaitStrategy差不多，对CPU的消耗也类似，但其对生产者线程的影响最小，适合用于异步日志类似的场景
		 * YieldingWaitStrategy的性能是最好的，适合用于低延迟的系统。在要求极高性能且事件处理线数小于CPU逻辑核心数的场景中，推荐使用此策略；例如，CPU开启超线程的特性
		 */
		Disruptor<LongEvent> disruptor = new Disruptor<>(eventFactory, ringBufferSize, threadFactory, producerType, waitStrategy);
		//连接消费事件方法
		disruptor.handleEventsWith(new LongEventHandler());
		disruptor.start();
		// Disruptor 的事件发布过程是一个两阶段提交的过程：
		// 发布事件
		//使用该方法获得具体存放数据的容器ringBuffer
		RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
		//
		LongEventProducer producer  = new LongEventProducer(ringBuffer);
		
		ByteBuffer byteBuffer = ByteBuffer.allocate(8); 
		for(long l = 0;l<10000;l++){
			byteBuffer.putLong(0,l);
			producer.onData(byteBuffer);
		}
		disruptor.shutdown();
		threadFactory.shutdown();
	}
}
